# _*_ coding: utf-8 _*_
# Copyright MiqroEra, Inc 2022. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License")
# Python Script for Ehanced Monte Carlo (EMC) Simulation
# The script is used to simulate the performance of a given system and generate input-files for LAMMPS simulation
# Author: MiqroEra

import os
import sys
import subprocess

def _get_platform():
    """
    The function is to determine the platform of the OS and return the corresponding executable file name.
    :return: emc_exec: the name of the executable file 
    """
    if sys.platform.startswith('linux'):
        emc_exec = 'emc_linux64'
    elif sys.platform.startswith('darwin'):
        emc_exec = 'emc_macos'
    elif sys.platform.startswith('win'):
        emc_exec = 'emc_win32.exe'
    else:
        raise RuntimeError('Unknown platform')
    _get_perl()
    return emc_exec


def _get_perl():
    """
    The function is to check whether perl is installed in the system.
    """
    perl = subprocess.run(['perl', '--version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if perl.returncode != 0:
        raise RuntimeError('Perl is not installed in the system. Please install it first.')
    else:
        print('Perl is installed in the system.')
    
    
def _get_emc_path():
    """
    The function is to get the path of the emc executable file.
    :return: emc_path: the path of the emc executable file
    """
    emc_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), _get_platform())
    return emc_path

def emc_setup(eshFile, *args):
    """
    The function is to setup the simulation with perl.
    :param eshFile: the name of the input file
    :param args: the arguments for the setup
    """
    emc_path = _get_emc_path()
    print('The path of the emc executable file is: {}'.format(emc_path))
    setup = subprocess.run(['perl', emc_path, eshFile, *args], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if setup.returncode != 0:
        raise RuntimeError('The setup of the simulation failed. Please check the input file.')
    else:
        print('The setup of the simulation is done.')

def emc_build(build_file):
    """
    The function is to build the simulation with perl.
    :param build_file: the name of the build file
    """
    emc_path = _get_emc_path()
    print('The path of the emc executable file is: {}'.format(emc_path))
    build = subprocess.run(['perl', emc_path, build_file], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if build.returncode != 0:
        raise RuntimeError('The build of the simulation failed. Please check the input file.')
    else:
        print('The build of the simulation is done.')

